<template>
  <div class="comp-full-calendar">
    <fc-header
      :current-month="currentMonth"
      :first-day="firstDay"
      :locale="locale"
      :settypesof="settypesof"
      @change="emitChangeMonth"
      :typesof="typesof"
      :goNext="goNext"
      :goPrev="goPrev"
    >
      <div slot="header-left">
        <slot name="fc-header-left"></slot>
      </div>

      <div slot="header-right">
        <slot name="fc-header-right"></slot>
      </div>
    </fc-header>
    <div class="full-calendar-body">
      <div class="weeks">
        <!-- 周一到周五 -->
        <strong
          class="week"
          v-for="dayIndex in 7"
          :key="dayIndex.value"
          :style="{display}"
        >{{ (dayIndex-2) | localeWeekDay(firstDay, locale) }}</strong>
      </div>
      <div class="dates" ref="dates">
        <div class="dates-bg">
          <div class="week-row" v-for="week in currentDates" :key="week.value">
            <div
              class="day-cell"
              v-for="day in week"
              :key="day.value"
              :class="{'today' : day.isToday,
              'not-cur-month' : !day.isCurMonth}"
              :style="{height}"
            >
              <p class="day-number">{{ day.monthDay }}</p>
            </div>
          </div>
        </div>

        <div class="dates-events">
          <div class="events-week" v-for="week in currentDates" :key="week.value">
            <el-container
              class="events-day"
              v-for="day in week"
              :key="day.value"
              :class="{'today' : day.isToday,
              'not-cur-month' : !day.isCurMonth}"
              @click.stop="dayClick(day, $event)"
              :style="{height}"
            >
              <el-header height class="day-number">{{day.monthDay}}</el-header>
              <el-main class="event-box">
                <event-card
                  :event="event"
                  :typesof="typesof"
                  :date="day.date"
                  :firstDay="firstDay"
                  v-for="event in scort(day)"
                  :key="event.key"
                  @click="eventClick"
                ></event-card>
              </el-main>
            </el-container>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script >
import dateFunc from "./dateFunc";
import weekFunc from "./weekFunc";
import dayFunc from "./dayFunc";
import moment from "moment";
import EventCard from "./eventCard.vue";
import header from "./header.vue";
import { sortBy } from "underscore";

export default {
  props: {
    events: {
      type: Array,
      default: function() {
        return [];
      }
    },
    locale: {
      type: String,
      default: "zh-cn"
    },
    firstDay: {
      type: [Number, String],
      validator(val) {
        let res = parseInt(val);
        return res >= 0 && res <= 6;
      },
      default: 0
    }
  },
  components: {
    "event-card": EventCard,
    "fc-header": header
  },
  data() {
    return {
      currentMonth: moment().startOf("day"),
      isLismit: true,
      eventLimit: 3,
      eventLimits: 6,
      showMore: false,
      morePos: {
        top: 0,
        left: 0
      },
      selectDay: {},
      heightk: "112px",
      typesof: 1
    };
  },
  watch: {
    currentMonth(v) {
      this.$emit("changeMonth", v, this.typesof);
    },
    typesof(v) {
      this.$emit("changeMonth", this.currentMonth, v);
    }
  },
  computed: {
    currentDates() {
      if (this.typesof == 0) {
        return this.getCalendar();
      } else if (this.typesof == 1) {
        return this.getCalendars();
      } else if (this.typesof == 2) {
        return this.getCalendarss();
      }
      return [];
    },
    height() {
      const { typesof } = this;
      if (typesof === 0) {
        return "112px";
      }
      return "672px";
    },
    display() {
      const { typesof } = this;
      if (typesof === 2) {
        return "none";
      }
      return "block";
    }
  },
  methods: {
    scort(day) {
      return sortBy(day.events, v =>
        Number(v.schooltime.split("-")[0].split(":")[0])
      );
    },
    settypesof(v) {
      this.typesof = v;
    },
    emitChangeMonth(firstDayOfMonth) {
      this.currentMonth = firstDayOfMonth;
      this.$emit("changeMonth", firstDayOfMonth, this.typesof);
      // if (this.typesof == 0) {
      //   let start = dateFunc.getMonthViewStartDate(
      //     firstDayOfMonth,
      //     this.firstDay
      //   );
      //   let end = dateFunc.getMonthViewEndDate(firstDayOfMonth, this.firstDay);
      //   this.$emit("changeMonth", start, end, firstDayOfMonth);
      // } else if (this.typesof == 1) {
      //   let start = weekFunc.getMonthViewStartDate(
      //     firstDayOfMonth,
      //     this.firstDay
      //   );
      //   let end = weekFunc.getMonthViewEndDate(firstDayOfMonth, this.firstDay);
      //   this.$emit("changeMonth", start, end, firstDayOfMonth);
      // } else if (this.typesof == 2) {
      //   let start = dayFunc.getMonthViewStartDate(
      //     firstDayOfMonth,
      //     this.firstDay
      //   );
      //   let end = dayFunc.getMonthViewEndDate(firstDayOfMonth, this.firstDay);
      //   this.$emit("changeMonth", start, end, firstDayOfMonth);
      // }
    },
    // 日历42个格子
    getCalendar() {
      let monthViewStartDate = dateFunc.getMonthViewStartDate(
        this.currentMonth,
        this.firstDay
      );
      let calendar = [];
      // 排
      for (let perWeek = 0; perWeek < 6; perWeek++) {
        let week = [];
        // 列
        for (let perDay = 0; perDay < 7; perDay++) {
          week.push({
            // 42天从那号开始
            monthDay: monthViewStartDate.date(),
            // 现在是几号
            isToday: monthViewStartDate.isSame(moment(), "day"),
            //上个月几天尾巴
            isCurMonth: monthViewStartDate.isSame(this.currentMonth, "month"),
            weekDay: perDay,
            date: moment(monthViewStartDate),
            events: this.slotEvents(monthViewStartDate)
          });
          // 一天一天排列
          monthViewStartDate.add(1, "day");
        }

        calendar.push(week);
      }
      return calendar;
    },
    //周
    getCalendars() {
      let monthViewStartDate = weekFunc.getMonthViewStartDate(
        this.currentMonth,
        this.firstDay
      );
      let calendar = [];
      // 排
      for (let perWeek = 0; perWeek < 1; perWeek++) {
        let week = [];
        // 列
        for (let perDay = 0; perDay < 7; perDay++) {
          week.push({
            // 42天从那号开始
            monthDay: monthViewStartDate.date(),
            // 现在是几号
            isToday: monthViewStartDate.isSame(moment(), "day"),
            //上个月几天尾巴
            isCurMonth: monthViewStartDate.isSame(this.currentMonth, "month"),
            weekDay: perDay,
            date: moment(monthViewStartDate),
            events: this.slotEvents(monthViewStartDate)
          });
          // 一天一天排列
          monthViewStartDate.add(1, "day");
        }

        calendar.push(week);
      }
      return calendar;
    },
    //天
    getCalendarss() {
      let monthViewStartDate = dayFunc.getMonthViewStartDate(
        this.currentMonth,
        this.firstDay
      );
      let calendar = [];
      // 排
      for (let perWeek = 0; perWeek < 1; perWeek++) {
        let week = [];
        // 列
        for (let perDay = 0; perDay < 1; perDay++) {
          week.push({
            // 42天从那号开始
            monthDay: monthViewStartDate.date(),
            // 现在是几号
            isToday: monthViewStartDate.isSame(moment(), "day"),
            //上个月几天尾巴
            isCurMonth: monthViewStartDate.isSame(this.currentMonth, "month"),
            weekDay: perDay,
            date: moment(monthViewStartDate),
            events: this.slotEvents(monthViewStartDate)
          });
          // 一天一天排列
          monthViewStartDate.add(1, "day");
        }

        calendar.push(week);
      }
      return calendar;
    },
    slotEvents(date) {
      // find all events start from this date
      // 查找所有事件从此日期开始
      // let cellIndexArr = [];
      let thisDayEvents = this.events.filter(day => {
        let st = moment(new Date(day.start).toLocaleDateString(), "YYYY-MM-DD");
        let ed = moment(st);

        return date.isBetween(st, ed, null, "[]");
      });
      // sort by duration
      //按持续时间排序
      thisDayEvents.sort((a, b) => {
        if (!a.start) return 1;
        if (!b.start) return -1;
        return a.start - b.start;
      });

      // mark cellIndex and place holder
      // 标记cellIndex和占位符
      for (let i = 0; i < thisDayEvents.length; i++) {
        thisDayEvents[i].cellIndex = thisDayEvents[i].cellIndex || i + 1;
        thisDayEvents[i].isShow = true;
      }

      return thisDayEvents;
    },
    computePos(target) {
      let eventRect = target.getBoundingClientRect();
      let pageRect = this.$refs.dates.getBoundingClientRect();
      return {
        left: eventRect.left - pageRect.left,
        top: eventRect.top + eventRect.height - pageRect.top
      };
    },
    dayClick(day) {
      this.$emit("dayClick", day.date);
    },
    eventClick(event, jsEvent) {
      if (!event.isShow) return;

      jsEvent.stopPropagation();
      let pos = this.computePos(jsEvent.target);
      this.$emit("eventClick", event, jsEvent, pos);
    },
    goPrev() {
      let newMonth;
      if (this.typesof == 0) {
        // 月
        newMonth = moment(this.currentMonth)
          .subtract(1, "months")
          .startOf("month");
        this.$emit("change", newMonth);
      } else if (this.typesof == 1) {
        // 周
        newMonth = moment(this.currentMonth)
          .subtract(1, "weeks")
          .startOf("isoWeek");
        this.$emit("change", newMonth);
      } else if (this.typesof == 2) {
        //天
        newMonth = moment(this.currentMonth)
          .subtract(1, "days")
          .startOf("day");
        this.$emit("change", newMonth);
      }
      this.currentMonth = newMonth;
    },
    // 右
    goNext() {
      let newMonth;
      if (this.typesof == 0) {
        // 月
        newMonth = moment(this.currentMonth)
          .add(1, "months")
          .startOf("month");
      } else if (this.typesof == 1) {
        // 周
        newMonth = moment(this.currentMonth)
          .add(1, "weeks")
          .startOf("isoWeek");
      } else if (this.typesof == 2) {
        //天
        newMonth = moment(this.currentMonth)
          .add(1, "days")
          .startOf("day");
      }
      this.currentMonth = newMonth;
    }
  },
  filters: {
    localeWeekDay(weekday, firstDay, locale) {
      firstDay = parseInt(firstDay);
      const localMoment = moment().locale(locale);
      return localMoment.localeData().weekdaysShort()[(weekday + firstDay) % 7];
    }
  }
};
</script>
<style lang="scss" scoped>
.comp-full-calendar {
  // font-family: "elvetica neue", tahoma, "hiragino sans gb";
  padding: 20px;
  background: #fff;
  max-width: 960px;
  margin: 0 auto;
  ul,
  p {
    margin: 0;
    padding: 0;
  }
}

.full-calendar-body {
  margin-top: 20px;
  .weeks {
    display: flex;
    border-top: 1px solid #e0e0e0;
    border-bottom: 1px solid #e0e0e0;
    border-left: 1px solid #e0e0e0;
    .week {
      flex: 1;
      text-align: center;
      border-right: 1px solid #e0e0e0;
    }
  }
  .dates {
    position: relative;
    .week-row {
      width: 100%;
      // position:absolute;
      border-left: 1px solid #e0e0e0;
      display: flex;
      //每个格子的高度
      .day-cell {
        flex: 1;
        min-height: 112px;
        padding: 4px;
        border-right: 1px solid #e0e0e0;
        border-bottom: 1px solid #e0e0e0;
        .day-number {
          text-align: right;
        }
        &.today {
          background-color: #fcf8e3;
        }
        &.not-cur-month {
          .day-number {
            color: rgba(0, 0, 0, 0.24);
          }
        }
      }
    }
    .dates-events {
      position: absolute;
      top: 0;
      left: 0;
      z-index: 1;
      width: 100%;
      .events-week {
        display: flex;
        .events-day {
          cursor: pointer;
          flex: 1;
          // height: 121px;//////////////////////////////////////////////////////////////////////////////
          overflow: hidden;
          text-overflow: ellipsis;
          .day-number {
            text-align: right;
            padding: 4px 5px 4px 4px;
            opacity: 0;
          }
          &.not-cur-month {
            .day-number {
              color: rgba(0, 0, 0, 0.24);
            }
          }
          .event-box::-moz-scrollbar {
            width: 1px;
            height: 4px;
          }
          .event-box::-moz-scrollbar-thumb {
            border-radius: 5px;
            background: rgba(0, 0, 0, 0.2);
          }
          .event-box::-moz-scrollbar-track {
            border-radius: 0;
            background: rgba(0, 0, 0, 0.1);
          }
          .event-box::-webkit-scrollbar {
            width: 1px;
            height: 4px;
          }
          .event-box::-webkit-scrollbar-thumb {
            border-radius: 5px;
            background: rgba(0, 0, 0, 0.2);
          }
          .event-box::-webkit-scrollbar-track {
            border-radius: 0;
            background: rgba(0, 0, 0, 0.1);
          }
          .event-box {
            overflow-y: scroll;
            padding: 0;
          }
        }
      }
    }
    .more-events {
      position: absolute;
      width: 150px;
      z-index: 2;
      border: 1px solid #eee;
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
      .more-header {
        background-color: #eee;
        padding: 5px;
        display: flex;
        align-items: center;
        font-size: 14px;
        .title {
          flex: 1;
        }
        .close {
          margin-right: 2px;
          cursor: pointer;
          font-size: 16px;
        }
      }
      .more-body {
        height: 146px;
        overflow: hidden;
        .body-list {
          height: 144px;
          padding: 5px;
          overflow: auto;
          background-color: #fff;
          .body-item {
            cursor: pointer;
            font-size: 12px;
            background-color: #c7e6fd;
            margin-bottom: 2px;
            color: rgba(0, 0, 0, 0.87);
            padding: 0 0 0 4px;
            height: 18px;
            line-height: 18px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
      }
    }
  }
}
</style>